import {messages} from "share/common";
/**
 *  created by jsq on 2017/9/27
 */
import React from 'react'
import { connect } from 'react-redux'

import { Button, Form, Select,Input, Col, Row, Switch, message, Icon, DatePicker, InputNumber  } from 'antd';
import budgetService from 'containers/budget-setting/budget-organization/budget-control-rules/budget-control-rulles.service'
import config from 'config'
import menuRoute from 'routes/menuRoute'
import debounce from 'lodash.debounce';

import "styles/budget-setting/budget-organization/budget-control-rules/new-budget-control-rules.scss"
import { LanguageInput } from 'components/template';

const FormItem = Form.Item;
const Option = Select.Option;

class NewBudgetControlRules extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      loading: true,
      strategyGroup: [],
      startValue: null,
      endValue: null,
      i18n: {}
    };
    this.validateRuleCode = debounce(this.validateRuleCode,1000)
  }

  componentWillMount(){
    //加载页面时，获取启用的控制策略
    budgetService.getStrategy({organizationId: this.props.organization.id, isEnabled: true }).then((response)=>{
      if(response.status === 200){
        let strategyGroup = [];
        response.data.map((item)=>{
          let strategy = {
            id: item.id,
            key: item.controlStrategyCode,
            value: item.controlStrategyCode+" - "+item.controlStrategyName,
            title: item.controlStrategyName
          };
          strategyGroup.push(strategy);
        });
        this.setState({
          strategyGroup: strategyGroup
        })
      }
    })
  }

  //处理开始时间
  handleDisabledStartDate = (startValue) =>{

    if(!this.state.endValue || !startValue){
      return false
    }
    return startValue.valueOf() > this.state.endValue.valueOf();
  };

  HandleStartChange = (value) =>{
    this.onChange("startValue",value)
  };

  HandleEndChange = (value) =>{
    this.onChange("endValue",value)
  };

  onChange = (field, value) => {
    this.setState({
      [field]: value,
    });
  };

  handleDisabledEndDate = (endValue) =>{
    if (!this.state.startValue || !endValue) {
      return false;
    }
    return endValue.valueOf() <= this.state.startValue.valueOf();
  };

  //新建预算规则
  handleSave = (e) =>{
    e.preventDefault();
    const { i18n } = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.organizationId = this.props.organization.id;
        values.strategyGroupId = values.controlStrategy.key;
        budgetService.addRule({ ...values, ...{ i18n } })
          .then((response) => {
            if (response.status === 200) {
              message.success(messages('budget-setting.key31'/*保存成功！*/)); /*保存成功！*/
              this.context.router.push(menuRoute.getMenuItemByAttr('budget-organization', 'key')
                  .children
                  .budgetControlRulesDetail
                  .url
                  .replace(':id', this.props.params.id)
                  .replace(':ruleId', response.data.id));
            }
          })
          .catch((e) => {
            if (e.response) {
              message.error(`${messages('common.save.filed')}, ${e.response.data.message}`);
            }
          })
          .finally(() => {
            this.setState({ loading: false });
          });
      }
    });
  };

  handleCancel = (e) =>{
    e.preventDefault();
    this.context.router.push(menuRoute.getMenuItemByAttr('budget-organization', 'key').children.budgetOrganizationDetail.url.replace(':id', this.props.params.id)+ '?tab=RULE');
  };

  validateRuleCode = (item,value,callback)=>{
    budgetService.getRuleByOptions({organizationId: this.props.params.id,controlRuleCode: value}).then((response)=>{
      let flag = false;
      if(response.data.length > 0 ){
        response.data.map((item)=>{
          if(item.structureCode === value) {
            flag = true;
          }
        })
      }
      flag >0 ? callback(messages('budget-setting.key37'/*该预算规则代码已存在*/)) : callback();
    });
  };

  handleSelect=()=>{
    let value = this.props.form.getFieldValue("controlStrategy");
    if(typeof value !== 'undefined'){
      let controlStrategy = {
        key: value.key,
        label: value.title,
        title: value.title
      };
      this.props.form.setFieldsValue({"controlStrategy": controlStrategy})
    }
  };

  handleI18n = (name, value) => {
    let { i18n, controlRuleName } = this.state;
    i18n.controlRuleName = value;
    controlRuleName = name;
    this.setState({ controlRuleName, i18n });
  };


  render(){
    const { getFieldDecorator } = this.props.form;
    const { strategyGroup, startValue, endValue, controlRuleName, i18n } = this.state;

    return(
      <div className="new-budget-control-rules">
        <div className="budget-control-rules-form">
          <Form onSubmit={this.handleSave} className="budget-control-rules-form">
            <Row gutter={60}>
              <Col span={8}>
                <FormItem
                  label={ messages('budget-setting.key19'/*控制规则代码*/) /*业务规则代码*/}
                  colon={true}>
                  {getFieldDecorator('controlRuleCode', {
                    rules:[
                      {required:true,message: messages('common.please.enter')},
                      {
                        validator:(item,value,callback)=>this.validateRuleCode(item,value,callback)
                      }
                    ]
                  })(
                    <Input placeholder={ messages('common.please.enter')}/>)
                  }
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem
                  label={ messages('budget-setting.key20'/*控制规则名称*/) /*控制规则名称*/}
                  colon={true}>
                  {getFieldDecorator('controlRuleName', {
                    rules:[
                      {required:true,message: messages('common.please.enter')},
                    ]
                  })(
                    <LanguageInput
                      name={controlRuleName}
                      i18nName={i18n.controlRuleName || null}
                      nameChange={this.handleI18n}
                      placeholder={messages('common.please.enter')/* 请输入 */}/>)}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem
                  label= {messages('budget-setting.key21'/*控制策略*/)}
                  colon={true}>
                  {getFieldDecorator('controlStrategy', {
                    rules:[
                      {required:true,message: messages('common.please.enter')},
                    ]
                  })(
                    <Select
                      getPopupContainer={triggerNode => triggerNode.parentNode}
                      labelInValue
                      onBlur={this.handleSelect}
                      placeholder={ messages('common.please.select')}>
                      {strategyGroup.map((item)=><Option key={item.id} value={item.id}  title={item.title}>{item.value}</Option>)}
                    </Select>)
                  }
                </FormItem>
              </Col>
            </Row>
            <Row gutter={60}>
              <Col span={8}>
                <Col span={11}>
                  <FormItem
                    label={messages('budget-setting.key22'/*有效日期*/) /*有效日期*/}
                    colon={true}>
                    {getFieldDecorator('startDate', {
                      rules:[
                        {required:true,message:messages('common.please.enter')},
                        {
                          validator:(item,value,callback)=>{
                            if(value === "undefined" || value === ""){
                              callback();
                              return
                            }
                            callback();
                          }
                        }
                      ]
                    })(
                      <DatePicker
                        placeholder={messages('budget-setting.key38'/*起始*/)}
                        setFieldsValue={startValue}
                        onChange={this.HandleStartChange}
                        disabledDate={this.handleDisabledStartDate}/>)
                    }
                  </FormItem>
                </Col>
                <Col span={11} offset={2}>
                  <FormItem
                    label=" "
                    colon={false}>
                    {getFieldDecorator('endDate', {
                      rules:[
                        {
                          validator:(item,value,callback)=>{
                            if(value === "undefined" || value === ""){
                              callback(messages('budget-setting.key39'/*请选择结束时间*/));
                              return
                            }
                            callback()
                          }
                        }
                      ]
                    })(
                      <DatePicker
                        placeholder={messages('budget-setting.key40'/*结束*/)}
                        setFieldsValue={endValue}
                        onChange={this.HandleEndChange}
                        disabledDate={this.handleDisabledEndDate}/>)
                    }
                  </FormItem>
                </Col>
              </Col>
              <Col span={6}>
                <FormItem
                  label={messages('budget-setting.key23'/*优先级*/) /*优先级*/}
                  colon={true}>
                  {getFieldDecorator('priority', {
                    rules:[
                      {required:true,message:messages('common.please.enter')},
                      {
                        validator:(item,value,callback)=>{
                          if(value === "undefined" || value === ""){
                            callback();
                            return
                          }
                          callback();
                        }
                      }
                    ]
                  })(
                    <InputNumber min={0} precision={0}  placeholder={messages('common.please.enter')}/>)
                  }
                </FormItem>
              </Col>
            </Row>
            <Button type="primary" htmlType="submit">{messages('common.save') /*保存*/}</Button>
            <Button onClick={this.handleCancel} style={{ marginLeft: 8 }}> {messages('common.cancel') /*取消*/}</Button>
          </Form>
        </div>
      </div>
    )
  }
}

NewBudgetControlRules.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    organization: state.budget.organization
  }
}

const WrappedNewBudgetControlRules = Form.create()(NewBudgetControlRules);
export default connect(mapStateToProps)(WrappedNewBudgetControlRules);
